package com.androsz.ramdroidx;

public enum MemoryStorageUnit {
	BYTE("B", 1L),
	KILOBYTE("KB", 1L << 10),
	MEGABYTE("MB", 1L << 20),
	GIGABYTE("GB", 1L << 30);/*
							 * , TERABYTE ("TB", 1L << 40), PETABYTE ("PB", 1L
							 * << 50), EXABYTE ("EB", 1L << 60);
							 */

	public static final MemoryStorageUnit BASE = BYTE;
	private static java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
	static {
		nf.setGroupingUsed(false);
		nf.setMinimumFractionDigits(0);
		nf.setMaximumFractionDigits(2);
		nf.setMaximumIntegerDigits(3);
	}

	public static MemoryStorageUnit of(final long number) {
		final long n = number > 0 ? -number : number;
		if (n > -(1L << 10)) {
			return BYTE;
		} else if (n > -(1L << 20)) {
			return KILOBYTE;
		} else if (n > -(1L << 30)) {
			return MEGABYTE;
		} else if (n > -(1L << 40)) {
			return GIGABYTE;
		} /*
		 * else if (n > -(1L << 50)) { return TERABYTE; } else if (n > -(1L <<
		 * 60)) { return PETABYTE; } else { // n >= Long.MIN_VALUE return
		 * EXABYTE; }
		 */
		return null;
	}

	private final String symbol;

	private final long divider; // divider of BASE unit

	MemoryStorageUnit(final String name, final long divider) {
		symbol = name;
		this.divider = divider;
	}

	public String format(final long number) {
		return format(number, false);
	}

	public String format(final long number, final boolean showUnits) {
		return nf.format((double) number / divider) + (showUnits ? " " + symbol : "");
	}

	public String getUnits() {
		return symbol;
	}

}